#!/usr/bin/env python
from duckietown_utils import get_machines_files_path
from duckietown_utils.cli import D8App
from duckietown_utils.file_utils import write_data_to_file
from easy_algo import get_easy_algo_db


class CreateMachines(D8App):
    """ Creates the machines file. """

    def define_program_options(self, params):
        params.add_flag(
            'print', help="If true, print instead of writing to file.")

    def go(self):
        robots = get_scuderia_contents()
        machines_contents = create_machines(robots)
        fn = get_machines_files_path()
        if getattr(self.options, 'print'):
            print(machines_contents)
        else:

            write_data_to_file(machines_contents, fn)

def get_scuderia_contents():
    db = get_easy_algo_db()
    robots = db.query_and_instance('robot', 'all')
    return robots

    
def create_machines(scuderia_contents):
    """ Returns XML string """

    start = """<!-- DO NOT MODIFY: this is autogenerated -->
    <launch>
    <arg name="env_script_path" default="~/duckietown/environment.sh"/>
    """

    def make_line(name, entry):
        #         space = " "*(13-len(entry.robot_name))
        p = """<machine name="%s"  address="%s.local" user="%s" env-loader="$(arg env_script_path)"/>"""
        return p % (name, entry.hostname,  entry.username)

    names = sorted(scuderia_contents)

    s = start
    for name in names:
        entry = scuderia_contents[name]
        s += '\n   ' + make_line(name, entry)

    s += '\n</launch>\n'
    return s
